"use strict";

import Vue from "vue";
import axios from "axios";
// 这个的 store 相当于组件中的 this.$soute
import store from "../store/index";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
    baseURL: "http://47.115.51.185/api",
    // baseURL: process.env.baseURL || process.env.apiUrl || ""
    // timeout: 60 * 1000, // Timeout
    // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

// 发送请求前
_axios.interceptors.request.use(
    function (config) {
        // 修改loding的状态
        store.commit("changeLoding", "2");
        // 如果vuex中有token,我们就可以在每一次请求前添加一个token
        if (store.getters.mytoken) {
            config.headers = {
                "Authori-zation": "Bearer " + store.getters.mytoken,
            };
        }
        // Do something before request is sent
        return config;
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// 响应请求后
_axios.interceptors.response.use(
    function (response) {
        // Do something with response data
        // 修改loding的状态
        store.commit("changeLoding", "1");

        if (response.data) {
            if (response.data.data) return response.data.data;

            return response.data;
        }

        return response;
    },
    function (error) {
        // Do something with response error
        return Promise.reject(error);
    }
);
function Plugin() {}
Plugin.install = function (Vue) {
    Vue.axios = _axios;
    window.axios = _axios;
    Object.defineProperties(Vue.prototype, {
        axios: {
            get() {
                return _axios;
            },
        },
        $axios: {
            get() {
                return _axios;
            },
        },
    });
};

Vue.use(Plugin);

// 公开接口改为axios对象
export default _axios;
